package com.nq.utils.smsUtil;

import com.alibaba.fastjson2.JSONObject;
import com.nq.controller.SmsApiController;
import com.nq.utils.DateTimeUtil;
import com.nq.utils.HttpClientRequest;
import com.nq.utils.Md5Utils;
import com.nq.utils.PropertiesUtil;
import com.nq.utils.pay.CmcPayOuterRequestUtil;
import com.nq.utils.redis.RedisShardedPoolUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class SmsUtil {
    private static final Logger log = LoggerFactory.getLogger(SmsApiController.class);

    public String sendSMS(String telephone) throws Exception {
        String code = RandomStringUtils.randomNumeric(4);
        CmcPayOuterRequestUtil requestUtil = new CmcPayOuterRequestUtil();

        String sign = "【悦溪盛弘】";
        String uid = "YQHL";
        String key = "YQHL123456";
        String userid = "639";
        String timestamp = DateTimeUtil.dateToStr2(new Date());
        String signStr = uid+key+timestamp;
        signStr = Md5Utils.md5_32(signStr);

        String sendTime = "";
        String smscontent = sign+"您的注册验证码是" + code + "。请在5分钟内使用";

        try {
            uid = URLEncoder.encode(uid,"UTF-8");
        } catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }

        String url ="http://47.92.203.40:8888/v2sms.aspx";
        log.info("smsurl"+url);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("action","send");
        map.put("userid",userid);
        map.put("timestamp",timestamp);
        map.put("sign",signStr);
        map.put("mobile",telephone);
        map.put("content",smscontent);
        map.put("sendTime","");
        map.put("rt","json");
        String result = HttpClientRequest.doPost(url,map);//"{\"ReturnStatus\":\"Success\",\"Message\":\"ok\",\"RemainPoint\":1,\"TaskID\":522690,\"SuccessCounts\":1}";
        log.info("smsresult="+result+"==code="+code);
        JSONObject json = JSONObject.parseObject(result);
        String status =  json.getString("ReturnStatus");
        if (status.equals("Success")) {
            String keys = "AliyunSmsCode:" + telephone;
            RedisShardedPoolUtils.setEx(keys, code, 5400);
            return code;
        } else {
            return "";
        }
    }
}
